package remoteControlSpy;

import java.io.IOException;

import os_listener.OS_Listener;
import os_listener.UpdatesFromServer;

/**
 * this class is the model class of the service
 */
public class ServiceManager 
{
	OS_Listener osl;
	UpdatesFromServer ufs;
	
	/**
	 * A handle to the unique ServiceMangaer instance.
	 */
	static private ServiceManager instance = null;
	//for the singleton
	private static Object someObject=new Object();
	
	// the private constructor of this class
	private ServiceManager() throws IOException 
	{
		osl = OS_Listener.getInstance();
		ufs = UpdatesFromServer.getInstance();
	}
	
	 /**
	 * @return The unique instance of this class.
	 * @throws IOException 
	 */
	static public ServiceManager getInstance()
	{
		if(null == instance) 
		{
			//to insure that the time slice doesn't cause the creation of 2 instances
			synchronized (someObject) 
			{
				if (null == instance)
					try 
					{
						instance = new ServiceManager();
					} 
					catch (IOException e) {}
			}
		}
	    return instance;
	}

	/**
	 * this function stops the service actions
	 * @throws IOException
	 */
	void stopTheService() throws IOException
	{
		// the case that the OS listener is working
		if(osl.getStop() == false)
		{
			// stops the OS listener
			osl.setStop(true);
		}
		// the case that the updates from server is working
		if(ufs.getStop() == false)
		{
			// stops the updates from server
			ufs.setStop(true);
		}
	}
	
	/**
	 * this function starts the service actions
	 * @throws IOException
	 */
	void  startTheService() throws IOException
	{
		osl.setStop(false);
		ufs.setStop(false);
		Thread t = new Thread(osl);
		Thread t2 = new Thread(ufs);
		// start the threads
		t.start();
		t2.start();
	}	
}
